package cn.kwq.project_manger.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.kwq.project_manger.pojo.QMsg;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Slf4j
@Component
public class TaskService {

    @Autowired
    JPAQueryFactory jpaQueryFactory;

    /**
     * 定时删除过期信息
     */
    @Async("taskExecutor") // 异步执行，线程之间不会互相干扰
    @PostConstruct//每次执行项目就执行
    @Scheduled(cron =" 0 30 4 * * ?" )//每日4：30触发
    @Transactional(rollbackFor = Exception.class)
    public void MsgTask(){
        try {
            QMsg msg = QMsg.msg1;
            Date lastMonth = DateUtil.lastMonth();
            Date lastLastMonth = DateUtil.offsetMonth(lastMonth, -1);
            //筛选应该删除的数组
            List<Long> deleteId = jpaQueryFactory.select(msg.msgId)
                    .from(msg)
                    .where(msg.updateDate.before(lastMonth))//一个月未修改
                    .where(msg.createdDate.before(lastLastMonth))//创建时间超2个月
                    .fetch();
            if (deleteId == null || ObjUtil.isEmpty(deleteId)) {
                log.info("今日无需删除信息");
                return;
            }
            if (deleteId.get(0) == null || ObjUtil.isEmpty(deleteId.get(0))) {
                log.info("今日无需删除信息");
                return;
            }
            //执行删除
            Optional.ofNullable(deleteId).ifPresent(delIds -> {
                log.info("今日删除的消息组：" + delIds);
                jpaQueryFactory.delete(msg)
                        .where(msg.msgId.in(delIds))
                        .execute();
            });
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getCause().getMessage());
            log.error(e.getMessage());
        }
    }





}
